﻿using System;
using System.ComponentModel;
using System.Threading;
using Castle.DynamicProxy;
using Sapit.Helpers;
using Sapit.Windsor.Attributes;

namespace Sapit.Windsor
{
    public class TimeoutInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            var timeout = AttributeHelper.GetAttributeIfPresent<TimeoutAttribute>(invocation.Method);
            if (timeout != null)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.WorkerSupportsCancellation = true;
                worker.DoWork += (sender, e) =>
                {
                    invocation.Proceed();
                };
                worker.RunWorkerAsync();
                DateTime startTime = DateTime.Now;
                DateTime maxEndTime = startTime.AddMilliseconds(timeout.TimeoutMilliseconds);
                while (worker.IsBusy && DateTime.Now < maxEndTime)
                {
                    Thread.Sleep(50);
                }
                if (invocation.ReturnValue == null)
                {
                    worker.CancelAsync();
                    worker.Dispose();
                    throw new TimeoutException(string.Format("Timeout expired. Operation took longer than {0} milliseconds.", timeout.TimeoutMilliseconds));
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
    }
}
